const WSjwtVerify = (ws, req, next) => {

	let authorization = req.params.wtoken;
	let token = '';
	let obj = {
		type: -1, //token问题
		code: 401,
		message: "token problem"
	}
	try {
		if (authorization === "" || authorization === undefined) {
			obj.message = "缺少token参数"
			throw new Error(obj.message);
		}
		if (authorization.includes('Bearer')) {
			token = authorization.replace('Bearer ', '');
		} else {
			token = authorization;
		}
		jwt.verify(token, secretKey, (error, data) => {
			if (error) {
				obj.message = "无效token"
				throw new Error(obj.message);
			} else {
				ws.user = data;
				ws.shsImUserInfo = {
					fromId: data.fromId,
					fromName: data.fromName,
					fromUrl: data.fromUrl,
					token: token
				}
				next();
			}
		});
	} catch (e) {

		if (e.message === "token problem" || e.message === "无效token" || e.message === "缺少token参数") {
			ws.send(JSON.stringify(obj));
			handlerOnline(0, req.params.wid, req.params.wname, req.params.wtoken); //发送信息
			return;
		}
		obj.message = e.message || "ws-token--未知问题"
		ws.send(JSON.stringify(obj));
	}

};

/**
 * api token verify
 */
const jwtVerify = (req, res, next) => {

	let authorization = req.headers.authorization;

	let token = '';
	let obj = {
		type: -1, //token问题
		code: 401,
		message: "token problem"
	}

	try {
		if (authorization === "" || authorization === undefined) {
			obj.message = "缺少token参数"
			throw new Error(obj.message);
			return
		}
		if (authorization.includes('Bearer')) {
			token = authorization.replace('Bearer ', '');
		} else {
			token = authorization;
		}
		jwt.verify(token, secretKey, (error, data) => {
			if (error) {
				obj.message = "无效token"
				throw new Error(obj.message);
			} else {
				req.shsImUserInfo = {
					fromId: data.fromId,
					fromName: data.fromName,
					fromUrl: data.fromUrl,
					token: token
				}
				next();
			}
		});
	} catch (e) {

		let fromId = req.query.fromId || req.params.fromId || req.body.fromId;
		if (e.message === "token problem" || e.message === "无效token" || e.message === "缺少token参数") {
			res.send(JSON.stringify(obj));
			handlerOnline(0, fromId, "", req.params.wtoken); //发送信息
			return;
		}
		obj.message = e.message || "ws-token--未知问题"
		res.send(JSON.stringify(obj));

	}

};

module.exports = {
	jwtVerify,
	WSjwtVerify
}

// 使用req.auth 获取加密数据
// app.use(expressjwt({
// 	secret: secretKey,
// 	algorithms: ["HS256"]
// }).unless({
// 	path: [/^\/user\//, /^\/ws\//]
// }))